'use strict';
/**
 * Created by FreezeSoul on 2015/10/13.
 */
define([
        'angular',
        'jquery',
        'app/core/util',
        'adConfig',
        'jStorage',
        'app/modules/page/define',
        'app/modules/page/services/page',
        'app/modules/page/controllers/page-setting',
        'app/modules/page/controllers/page-export',
        'app/modules/page/controllers/page-import',
        'app/modules/index/services/index',
        'app/modules/folder/services/folder-tree',
        'app/modules/page/directives/layout-container',
        'app/modules/page/directives/scroll-container'
    ],
    function (angular, $, Util, adConfig) {
        angular.module('ad.page')
            .controller('adPageEditController', ['$scope', '$filter', '$state', '$stateParams', '$uibModal', '_', 'Notification', 'adFolderEditService', 'adIndexEditService', 'adPageEditService'
                , function ($scope, $filter, $state, $stateParams, $uibModal, _, Notification, folderService, chartsService, service) {

                    $scope.Page = {};

                    $scope.pageCharts = [];

                    $scope.layoutPlugin = null;

                    $scope.LayoutPageId = undefined;

                    $scope.pageWidth = "";
                    $scope.pageHeight = "";
                    $scope.pageSize = undefined;

                    $scope.treeOptions = {
                        nodeChildren: "children",
                        dirSelectable: false,
                        allowDeselect: false,
                        isSelectable: function (node) {
                            return node.type !== "folder";
                        },
                        injectClasses: {
                            "iExpanded": "glyphicon glyphicon-chevron-down",
                            "iCollapsed": "glyphicon glyphicon-chevron-right"
                        }
                    };

                    $scope.treeModels = [];

                    $scope.expandedFolders = [];

                    $scope.selected = undefined;

                    $scope.sideBarStateShow = true;

                    $scope.$stateParams = $stateParams;

                    $scope.setSize = function () {
                        var width = parseInt($scope.pageWidth);
                        var height = parseInt($scope.pageHeight);
                        if (width >= 0 && height >= 0) {
                            $scope.pageSize = width + "X" + height;
                            $.jStorage.set("page-size-" + $scope.$stateParams.pageid, $scope.pageSize);
                        } else {
                            Notification.error('输入有误！');
                        }
                    };

                    $scope.resetSize = function () {
                        $scope.pageWidth = "";
                        $scope.pageHeight = "";
                        $scope.pageSize = 0 + "X" + 0;
                        $.jStorage.set("page-size-" + $scope.$stateParams.pageid, $scope.pageSize);
                    };

                    $scope.loadSize = function () {
                        var size = $.jStorage.get("page-size-" + $scope.$stateParams.pageid);
                        if (size) {
                            $scope.pageWidth = size.split('X')[0] == 0 ? "" : size.split('X')[0];
                            $scope.pageHeight = size.split('X')[1] == 0 ? "" : size.split('X')[1];
                            $scope.pageSize = size;
                        }
                    };

                    $scope.gotoDefault = function () {
                        $state.go("editor.page.search");
                    };

                    $scope.switchTreeSidebar = function () {
                        $scope.sideBarStateShow = !$scope.sideBarStateShow;
                    };

                    $scope.itemSelected = function (node) {
                        if ($scope.layoutPlugin) {
                            $scope.layoutPlugin.add({"chartId": node.id});
                        }
                    };

                    $scope.settings = function () {
                        var modalInstance = $uibModal.open({
                            animation: true,
                            templateUrl: 'app/modules/page/views/page-setting.tpl.html',
                            controller: 'adPageSettingController',
                            size: 'lg',
                            resolve: {
                                item: function () {
                                    return $scope.Page;
                                },
                                layout: function () {
                                    return $scope.layoutPlugin;
                                }
                            }
                        });

                        modalInstance.result.then(function (page) {
                            $scope.Page = page;
                            $scope.save();
                        }, function () {
                        });
                    };

                    $scope.loadPage = function () {
                        var pageId = $scope.$stateParams.pageid;
                        service.loadPage(pageId).then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                $scope.Page = obj.data;
                                $scope.LayoutPageId = obj.data.page_id;
                                $scope.loadSize();
                            }
                        });
                    };

                    $scope.loadFolders = function () {
                        folderService.getFolders(adConfig.chartFolderType).then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                var rootItemId = adConfig.rootFolderId;
                                var rootItem = {
                                    "name": "指标根目录",
                                    "id": rootItemId,
                                    "type": "folder",
                                    "data": {folder_id: rootItemId},
                                    "children": [],
                                    "parent": {}
                                };
                                $scope.expandedFolders.push(rootItem);
                                var convertFolderToTreeNode = function (currentParentId, parentFolderItem) {
                                    var folders = _.filter(obj.data, function (item) {
                                        return item.folder_parent == currentParentId
                                    });
                                    folders = _.sortBy(folders, function (item) {
                                        return item.folder_name
                                    });
                                    _.each(folders, function (folder) {
                                        var currentId = folder.folder_id;
                                        var currentItem = {
                                            "name": folder.folder_name,
                                            "id": folder.folder_id,
                                            "type": "folder",
                                            "data": folder,
                                            "children": [],
                                            "parent": parentFolderItem
                                        };
                                        convertFolderToTreeNode(currentId, currentItem);
                                        parentFolderItem.children.push(currentItem);
                                    })
                                };
                                convertFolderToTreeNode(rootItemId, rootItem);

                                $scope.loadCharts(rootItem);
                            }
                        }, function () {
                        });
                    };

                    $scope.loadCharts = function (rootItem) {
                        chartsService.getCharts().then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                var walkThroughFolders = function (folder) {
                                    var folderId = folder.id;
                                    var charts = _.filter(obj.data, function (item) {
                                        return item.chart_folder_id == folderId
                                    });
                                    charts = _.sortBy(charts, function (chart) {
                                        return chart.chart_name;
                                    });
                                    _.each(charts, function (chart) {
                                        var item = {
                                            "name": chart.chart_name,
                                            "id": chart.chart_id,
                                            "type": "element",
                                            "data": chart,
                                            "children": [],
                                            "parent": folder
                                        };
                                        folder.children.push(item);
                                    });
                                    var childFolders = _.filter(folder.children, function (item) {
                                        return item.type == "folder"
                                    });
                                    _.each(childFolders, function (folder) {
                                        walkThroughFolders(folder);
                                    })
                                };
                                walkThroughFolders(rootItem);

                                $scope.treeModels.push(rootItem);
                            }
                        });
                    };

                    $scope.save = function () {
                        $scope.Page.page_data = angular.toJson($scope.layoutPlugin.getOption());

                        service.updatePage($scope.Page).then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                Notification.success('保存成功！');
                                $state.go('editor.page.search');
                            }
                        });
                    };

                    $scope.refreshChartList = function () {
                        if ($scope.setTimeoutHandle) {
                            clearTimeout($scope.setTimeoutHandle)
                        }
                        $scope.setTimeoutHandle = setTimeout(function () {
                            $scope.pageCharts = [];
                            for (var i = 0; i < window.__layoutObjects.length; i++) {
                                var chartObj = window.__layoutObjects[i];
                                $scope.pageCharts.push({
                                    chartObj: chartObj,
                                    chartName: chartObj.__name,
                                    menuId: Util.newUUID()
                                });
                            }
                            $scope.$digest();
                        }, 1000);
                    };

                    $scope.bindLayoutEvent = function () {
                        $scope.layoutPlugin._globleEmitter.addListener("addChart", $scope.refreshChartList);
                        $scope.layoutPlugin._globleEmitter.addListener("removeChart", $scope.refreshChartList);
                    };

                    $scope.selectChart = function (chart) {
                        if (chart.chartObj.__box) {
                            if ($scope.layoutPlugin._layoutType == "free") {
                                $(".scroll-container").animate({
                                    scrollTop: chart.chartObj.__box.position().top - 100,
                                    scrollLeft: chart.chartObj.__box.position().left - 100
                                }, 1000, function () {
                                    var flash = function () {
                                        $(chart.chartObj.__box).css({
                                            borderColor: 'red',
                                            backgroundColor: 'yellow'
                                        });
                                        setTimeout(function () {
                                            $(chart.chartObj.__box).css({
                                                borderColor: 'gray',
                                                backgroundColor: ''
                                            });
                                            setTimeout(function () {
                                                if (flash.index === undefined) flash.index = 0;
                                                flash.index++;
                                                if (flash.index < 3) {
                                                    flash()
                                                }
                                            }, 500);
                                        }, 500);
                                    };
                                    flash();
                                });
                            } else if ($scope.layoutPlugin._layoutType == "grid") {
                                var flash = function () {
                                    $(chart.chartObj.__box).find(".lm_content").css({
                                        borderColor: 'red',
                                        backgroundColor: 'yellow'
                                    });
                                    setTimeout(function () {
                                        $(chart.chartObj.__box).find(".lm_content").css({
                                            borderColor: '#ccc',
                                            backgroundColor: '#F4F4F4'
                                        });
                                        setTimeout(function () {
                                            if (flash.index === undefined) flash.index = 0;
                                            flash.index++;
                                            if (flash.index < 3) {
                                                flash()
                                            }
                                        }, 500);
                                    }, 500);
                                };
                                flash();
                            }
                        }
                    };

                    $scope.refresh = function () {
                        if ($scope.Page.page_id) {
                            service.refreshPage($scope.Page.page_id).then(function (data) {
                                var obj = angular.fromJson(data);
                                if (obj.result == 'success') {
                                    Notification.success('刷新成功！');
                                }
                            });
                        }
                    };

                    $scope.export = function () {
                        var modalInstance = $uibModal.open({
                            animation: true,
                            templateUrl: 'app/modules/page/views/page-export.tpl.html',
                            controller: 'adPageExportController',
                            size: 'lg',
                            resolve: {
                                item: function () {
                                    return $scope.Page;
                                }
                            }
                        });

                        modalInstance.result.then(function (page) {
                        }, function () {
                        });
                    };

                    $scope.import = function () {
                        var modalInstance = $uibModal.open({
                            animation: true,
                            templateUrl: 'app/modules/page/views/page-import.tpl.html',
                            controller: 'adPageImportController',
                            size: 'lg',
                            resolve: {
                                item: function () {
                                    return $scope.Page;
                                }
                            }
                        });

                        modalInstance.result.then(function () {
                            Notification.success('导入成功！');
                            $state.go('editor.page.search');
                        }, function () {
                        });
                    };

                    $scope.menuHandle = function ($event, chart, actionType) {
                        if (chart.chartObj.__box && $scope.layoutPlugin._layoutType == "free") {
                            $(".scroll-container").animate({
                                scrollTop: chart.chartObj.__box.position().top - 100,
                                scrollLeft: chart.chartObj.__box.position().left - 100
                            }, 100, function () {
                                $scope.layoutPlugin._layoutPlugin._layout.objectMenuHandle($scope.layoutPlugin._layoutPlugin._layout, chart.chartObj.__layoutObject, actionType);
                            });
                        }
                    };

                    $scope.$on('$destroy', function () {
                        $scope.layoutPlugin._globleEmitter.removeListener("addChart", $scope.refreshChartList);
                        $scope.layoutPlugin._globleEmitter.removeListener("removeChart", $scope.refreshChartList);
                    });

                    $scope.loadFolders();
                    $scope.loadPage();
                }]);
    });